const http = require('http');

// 测试后端服务器连接
function testServerConnection(host, port) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: host,
      port: port,
      path: '/api/health',
      method: 'GET',
      timeout: 5000
    };

    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          console.log(`✅ 服务器连接成功: ${host}:${port}`);
          console.log('响应数据:', data);
          resolve(true);
        } else {
          console.log(`❌ 服务器响应错误: ${res.statusCode}`);
          reject(new Error(`HTTP ${res.statusCode}`));
        }
      });
    });

    req.on('error', (err) => {
      console.log(`❌ 连接失败: ${host}:${port} - ${err.message}`);
      reject(err);
    });

    req.on('timeout', () => {
      console.log(`⏰ 连接超时: ${host}:${port}`);
      req.destroy();
      reject(new Error('Connection timeout'));
    });

    req.end();
  });
}

// 测试多个地址
async function testAllConnections() {
  const testUrls = [
    { host: 'localhost', port: 3000 },
    { host: '127.0.0.1', port: 3000 },
    { host: '192.168.7.125', port: 3000 },
    { host: '192.168.1.100', port: 3000 },
    { host: '192.168.0.100', port: 3000 }
  ];

  console.log('🔍 开始测试服务器连接...\n');

  for (const url of testUrls) {
    try {
      await testServerConnection(url.host, url.port);
      console.log(`✅ 找到可用服务器: ${url.host}:${url.port}\n`);
      return;
    } catch (error) {
      console.log(`❌ ${url.host}:${url.port} 连接失败\n`);
    }
  }

  console.log('❌ 所有服务器地址都无法连接');
  console.log('请检查：');
  console.log('1. 后端服务器是否正在运行');
  console.log('2. 端口3000是否被占用');
  console.log('3. 防火墙是否阻止连接');
  console.log('4. IP地址是否正确');
}

// 运行测试
testAllConnections().catch(console.error);
